package nodes

import (
	"fmt"

	"example.com/dcache/rpcserver/client"
)

// HttpGetter implements interface NodeGetter, as a client,
// can get key's data from its brother server
// baseAddr is a remote server's base url, such as http://example.com/distributedcache/
type RpcHandler struct {
	baseAddr string
	rpclient *client.RpcClient
}

func NewRpcHandler(baseAddr string) *RpcHandler {
	r := &RpcHandler{
		baseAddr: baseAddr,
	}

	r.rpclient = client.NewRpcClient(r.baseAddr)

	return r
}

func (r *RpcHandler) SetGroup(group string) error {
	status := r.rpclient.SetGroup(group)

	if status == 200 {
		fmt.Println("setGroup by rpc")
		return nil
	}

	return fmt.Errorf("SetGroup rpc error")
}

func (r *RpcHandler) DeleteGroup(group string) error {
	status := r.rpclient.DeleteGroup(group)

	if status == 200 {
		fmt.Println("deleteGroup by rpc")
		return nil
	}

	return fmt.Errorf("DeleteGroup rpc error")
}

// Get gets data from remote server, by using http.Get()
func (r *RpcHandler) Get(group string, key string) ([]byte, error) {
	status, value := r.rpclient.Get(group, key)

	if status == 200 {
		fmt.Println("get by rpc")
		return []byte(value), nil
	}

	return nil, fmt.Errorf("Get rpc error")
}

// Set gets data from remote server, by using http.Get()
// This function is not correct, need modify later
func (r *RpcHandler) Set(group string, key string, value []byte) error {
	status := r.rpclient.Set(group, key, string(value))

	if status == 200 {
		fmt.Println("set by rpc")
		return nil
	}

	return fmt.Errorf("Set rpc error")
}

// Delete gets data from remote server, by using http.Get()
func (r *RpcHandler) Delete(group string, key string) error {
	status := r.rpclient.Delete(group, key)

	if status == 200 {
		fmt.Println("delete by rpc")
		return nil
	}

	return fmt.Errorf("Delete rpc error")
}

func (r *RpcHandler) GetBaseAddr() string {
	return r.baseAddr
}
